package com.ogms.dge.container.modules.data.converter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ogms.dge.container.modules.common.service.DataSourceService;
import com.ogms.dge.container.modules.data.entity.ServiceEntity;
import com.ogms.dge.container.modules.data.entity.SourceEntity;
import com.ogms.dge.container.modules.data.service.SourceService;
import com.ogms.dge.container.modules.data.vo.ServiceVo;
import com.ogms.dge.container.modules.sys.service.SysUserService;
import org.mapstruct.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @name: ServiceConverter
 * @description: TODO
 * @author: Lingkai Shi
 * @date: 9/23/2024 3:53 PM
 * @version: 1.0
 */
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface ServiceConverter {

    ObjectMapper objectMapper = new ObjectMapper();

    @Mapping(target = "type", ignore = true)
    @Mapping(target = "createUsername", ignore = true)
    @Mapping(target = "srcName", ignore = true)
    @Mapping(target = "configMap", ignore = true)
    ServiceVo po2Vo(ServiceEntity serviceEntity, @Context SysUserService userService, @Context SourceService sourceService, @Context DataSourceService dataSourceService) throws JsonProcessingException;

    @AfterMapping
    default void handleCustomFields(ServiceEntity serviceEntity, @MappingTarget ServiceVo serviceVo, @Context SysUserService userService, @Context SourceService sourceService, @Context DataSourceService dataSourceService) throws JsonProcessingException {
        serviceVo.setType(dataSourceService.getById(serviceEntity.getTypeId()).getName());
        serviceVo.setCreateUsername(userService.getById(serviceEntity.getCreateUserId()).getUsername());
        QueryWrapper queryWrapper = new QueryWrapper<SourceEntity>().eq("uuid", serviceEntity.getSrcUuid());
        serviceVo.setSrcName(sourceService.getOne(queryWrapper).getName());
        serviceVo.setConfigMap(objectMapper.readValue(serviceEntity.getConfig(), Map.class));
        serviceVo.setPathList(Arrays.stream(serviceEntity.getPath().split(","))
                .filter(Objects::nonNull).collect(Collectors.toList()));
    }

    default List<ServiceVo> poList2VoList(List<ServiceEntity> serviceEntityList, @Context SysUserService userService, @Context SourceService sourceService, @Context DataSourceService dataSourceService) {
        return serviceEntityList.stream()
                .map(service -> {
                    try {
                        return po2Vo(service, userService, sourceService, dataSourceService);
                    } catch (JsonProcessingException e) {
                        throw new RuntimeException(e);
                    }
                })
                .collect(Collectors.toList());
    }
}
